var mongoose = require('mongoose');
const Comment = require('../models/procomment.model');
//新建评论
exports.create = function(req, res, next) {
    const com = new Comment(req.body);
    console.log(com)
    com.save().then((data) => {
        res.json(data);
    });
}

exports.update = function(req, res, next) {
    const id = req.params.id;
    // res.send(id);
    Comment.findByIdAndUpdate(id, { $set: req.body }, { new: false })
        .then(data => {
            res.json(data); // 这里返回的数据是修改之前的数据，不是改之后的数据
        })
}

// 移除相应的id的数据
exports.remove = function(req, res, next) {
    const id = req.params.id;
    Comment.findByIdAndDelete(id, (err, data) => {
        res.json(data);
    })
}

// 这个暂时还没搞清楚
exports.list = function(req, res, next) {
    var page = req.body.page ? req.body.page : 1;
    var rows = req.body.rows ? req.body.rows : 5;

    var queryCondition = {}; //查询条件
    if (req.body.title && req.body.title.trim().length > 0) {
        title = req.body.title;
        queryCondition = {
            "title": new RegExp(title, 'i')
        }
    }
    //分类Id
    if (req.body.cateId && req.body.cateId.trim().length > 0) {
        cateId = req.body.cateId;
        queryCondition = Object.assign(queryCondition, {
            cateId: cateId
        })
    }
    //用户Id
    if (req.body.userId && req.body.userId.trim().length > 0) {
        userId = req.body.userId;
        queryCondition = Object.assign(queryCondition, {
            userId: userId
        })
    }
    //isHot
    if (req.body.isHot && req.body.isHot.trim().length > 0) {
        isHot = req.body.isHot;
        queryCondition = Object.assign(queryCondition, {
            isHot: isHot
        })
    }
    //isTop
    if (req.body.isTop && req.body.isTop.trim().length > 0) {
        isTop = req.body.isTop;
        queryCondition = Object.assign(queryCondition, {
            isTop: isTop
        })
    }
    //isPublish
    if (req.body.isPublish && req.body.isPublish.trim().length > 0) {
        isPublish = req.body.isPublish;
        queryCondition = Object.assign(queryCondition, {
            isPublish: isPublish
        })
    }

    console.log(queryCondition)
    Comment.paginate(queryCondition, { page: +page, limit: +rows }, function(err, result) {
        result.rows = result.docs;
        delete result.docs;
        res.json(result);
    });
}

// 查询相应id信息
exports.getData = function(req, res, next) {
    var id = req.params.id;
    Comment.findById(id).then(data => {
        res.json(data);
    })

}

exports.removes = function(req, res, next) {
    var ids = req.body.ids.split(',')
    if (ids.length > 0) {
        Comment.remove({ _id: { $in: ids } }).then(data => {
            res.json({ 'message': 'delete ok', status: 200 })
        })
    }
}